import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.util.StringTokenizer;


public class Bullet extends MovingObject
{
	public static final int RADIUS = 1;
	public static final double SPEED = ShipObject.MAX_SPEED*2;
	
	// keep track of who shot this bullet so that a ship can't shoot itself
	private ShipObject shooter;
	private BufferedImage image;
	
	private double lifetime; // time before bullet disappears, in pixels
	
	public boolean consumed;
	
	public Bullet(int x, int y, ShipObject shooter)
	{
		super(x,y);
		this.shooter = shooter;
		
		double direction = shooter.getDirection();
		vx = SPEED*Math.cos(direction);
		vy = SPEED*Math.sin(direction);
		
		lifetime = Math.min(AsteroidsGame.GAME_WIDTH, AsteroidsGame.GAME_HEIGHT);
		AsteroidsGame.soundManager.play(AsteroidsGame.laser);
		
		drawImage();
	}
	
	public Bullet(StringTokenizer strtok)
	{
		super();
		loadState(strtok);
		
		drawImage();
	}
	
	// implement superclass methods
	public BufferedImage getImage() { return image; }
	public int getWrapWidth() { return 0; }
	public int getWrapHeight() { return 0; }
	
	// Implement collision functions
	public CollisionType collisionType() { return CollisionType.POINT; }
	public double[] collisionData()
	{
		double[] point = {x, y};
		return point;
	}
	
	protected void loadState(StringTokenizer strtok) throws NumberFormatException
	{
		super.loadState(strtok);
		lifetime = Double.parseDouble(strtok.nextToken());
		int i = Integer.parseInt(strtok.nextToken());
		if(i == 1) // it is very important that the players get saved first
			shooter = AsteroidsGame.game.player1;
		else if(i == 2)
			shooter = AsteroidsGame.game.player2;
		else
			shooter = null; // this might cause strangeness with aliens, but oh well
	}
	protected String saveState()
	{
		String s = "Bullet " + super.saveState() + String.format("%f ", lifetime);
		if(shooter == AsteroidsGame.game.player1)
			s += "1\n";
		else if(shooter == AsteroidsGame.game.player2)
			s += "2\n";
		else
			s += "0\n";
		return s;
	}
	
	public boolean isShooter(SpaceObject o)
	{
		return o == shooter;
	}
	
	private void drawImage()
	{
		image = new BufferedImage(2*RADIUS + 1, 2*RADIUS + 1, BufferedImage.TYPE_INT_ARGB);
		Graphics2D g = image.createGraphics();
		g.setColor(Color.WHITE);
		g.drawOval(0,0, RADIUS*2, RADIUS*2);
		g.dispose();
		
	}
	
	// Overrides move() from movingObject
	public void move()
	{
		super.move();
		lifetime -= SPEED/FRAME_RATE;
		if(lifetime <= 0)
			delete();
	}
	
	// Overrides hit from SpaceObject
	//  a Bullet can be hit by an Asteroid, Spaceship, or AlienShip
	public boolean hit(SpaceObject by)
	{
		if(isShooter(by)) // no effect on the bullet's shooter
			return false;
		delete(); // otherwise the bullet is consumed; the other object will take care of destroying itself
		return true;
	}
}
